const mysql = require('mysql2/promise');

class Database {

  constructor(config) {
    config= {
      host: '127.0.0.1',  
      user: 'root',  
      password: '415304',  
      database: 'plmop',
      waitForConnections: true,
      connectionLimit: 10,
      queueLimit: 0,
      timezone: '+08:00',
      dateStrings: true,
      charset: 'utf8mb4' // 设置字符集为UTF-8
    };
    this.pool = mysql.createPool(config);
  }

  // 普通查询方法
  async query(sql, params) {
    const connection = await this.pool.getConnection();
    try {
      const [rows, _fields] = await connection.execute(sql, params);
      return rows;
    } finally {
      connection.release();
    }
  }

  // 封装执行方法
  async execute(sql, values) {
    let connection;
    try {
      connection = await this.pool.getConnection();
      const [results, fields] = await connection.execute(sql, values);
      return results;
    } catch (error) {
      throw error;
    } finally {
      if (connection) connection.release(); // 释放连接
    }
  }

  // 事务相关方法
  async getConnection() {
    return await this.pool.getConnection();
  }

  async beginTransaction(connection) {
    await connection.beginTransaction();
  }

  async commit(connection) {
    await connection.commit();
  }

  async rollback(connection) {
    await connection.rollback();
  }

  async close() {
    await this.pool.end();
  }

}

module.exports = Database;